package com.naiterui.ehp.bs.weixin.handler;

import static me.chanjar.weixin.common.api.WxConsts.EventType;

import com.naiterui.ehp.bs.weixin.service.WechatService;
import java.util.Map;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

/**
 * @author gaoll gll910802@163.com
 */
@Component
@AllArgsConstructor
public class MenuHandler extends AbstractHandler {

    private final WechatService wechatService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
        Map<String, Object> context, WxMpService weixinService,
        WxSessionManager sessionManager) {

        logger.info("MenuHandler , wxMessage={}", wxMessage);

        String msg = String.format("type:%s, event:%s, key:%s",
            wxMessage.getMsgType(), wxMessage.getEvent(),
            wxMessage.getEventKey());
        if (EventType.VIEW.equals(wxMessage.getEvent())) {
            return null;
        }

        if (EventType.CLICK.equals(wxMessage.getEvent())) {
            try {
                wechatService.menuClick(wxMessage.getFromUser(), wxMessage.getEventKey(), weixinService);
            } catch (WxErrorException e) {
                logger.error("menuClick faild ; error={}", e.getMessage());
            }
            return null;
        }

        return WxMpXmlOutMessage.TEXT().content(msg)
            .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
            .build();
    }

}
